﻿
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;

namespace Server
{
    class Program
    {
        static ServerPipe m_pServerPipe;

        static void Main(string[] args)
        {
            m_pServerPipe = new ServerPipe("SQUALL_PIPE", 0);
            m_pServerPipe.ReadDataEvent += M_pServerPipe_ReadDataEvent;
            m_pServerPipe.PipeClosedEvent += M_pServerPipe_PipeClosedEvent;
            m_pServerPipe.ConnectionEvent += M_pServerPipe_ConnectionEvent;
            Console.WriteLine("等待连接");
            while (true)
            {
                string result = Console.ReadLine();
                m_pServerPipe.Close();
                if (string.IsNullOrWhiteSpace(result))
                {
                    continue;
                }
                m_pServerPipe.SendBytes(Encoding.UTF8.GetBytes(result));
            }
        }
        /// <summary>
        /// 收到客户端连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void M_pServerPipe_ConnectionEvent(object sender, EventArgs e)
        {
            Console.WriteLine("收到客户端连接");
        }

        private static void M_pServerPipe_PipeClosedEvent(object sender, EventArgs e)
        {
            Debug.WriteLine("Server: Pipe was closed, shutting down");
            Console.WriteLine("客户端关闭");
        }

        private static void M_pServerPipe_ReadDataEvent(object sender, PipeEventArgs e)
        {
            // this gets called on an anonymous threade

            byte[] pBytes = e.Bytes;
            //File.WriteAllText(@"E:\资料\新建文本文档123.txt", Encoding.UTF8.GetString(pBytes).Trim(new char[] { '\0' }));
            //Console.WriteLine("写入文件："+ pBytes.Length);
            //Console.WriteLine(DateTime.Now);
            string szBytes = Encoding.Default.GetString(pBytes, 0, e.Length);
           Console.WriteLine("数据来着客户端：" + szBytes.Trim(new char[] { '\0' }));

            ////PipeCommandPlusString pCmd = serializer.Deserialize<PipeCommandPlusString>(szBytes.Trim(new char[] { '\0' }));
            //string szValue = pCmd.GetTransmittedString();

            //if (szValue == "CONNECT")
            //{
            //    Debug.WriteLine("Got command from client: " + pCmd.GetCommand() + "-" + pCmd.GetTransmittedString() + ", writing command back to client");
            //    PipeCommandPlusString pCmdToSend = new PipeCommandPlusString("SERVER", "CONNECTED");
            //    // fire off an async write
            //    Task t = m_pServerPipe.SendCommandAsync(pCmdToSend);
            //}
            //else
            //{
            //    Console.WriteLine("Data from client: " + szValue);
            //}
        }
    }
}
